<?php
class HB_Ident {
	function __construct() {
		db_register_table('ident');
	}

	public function remove($ident_id) {
		global $hbdb;
		$hbdb->query("DELETE FROM $hbdb->ident WHERE ident_id=$ident_id");
		return true;
	}
	
	public function update($values) {
		global $hbdb;
		extract($values);
		if (is_null($ident_id)
			|| $hbdb->get_var("SELECT COUNT(*) FROM $hbdb->ident WHERE ident_id = $ident_id")<=0) {
			$add_recode = true;
		}
		if ($add_recode) { // add a new ident
			if (empty($descrition)) return false;
			$description = $hbdb->escape($description);
			$api_key = $this->_gen_api_key();
			if (empty($status) || !in_array($status, array('enable','disable')) $status = 'enable';
			if (empty($stat_mode) || !in_array($stat_mode, array('public','private','password')) $stat_mode = 'public';
			if (empty($stat_pass)) {
				if ($stat_mode == 'password') $stat_pass = $this->_gen_api_key(8);
				else $stat_pass = '';
			}
			$sql = "INSERT INTO $hbdb->ident (description, api_key, status, stat_mode, stat_pass) VALUES ('$description', '$api_key', '$status','$stat_mode','$stat_pass')";
		} else {
			$r = $hbdb->get_row("SELECT * FROM $hbdb->ident WHERE ident_id = $ident_id");
			$this->_default_value($description,$r->description);
			$description = $hbdb->escape($description);
			$this->_default_value($api_key,$r->api_key);
			$this->_default_value($status,$r->status);
			$this->_default_value($stat_mode,$r->stat_mode);
			$this->_default_value($stat_pass,$r->stat_pass);
			$sql = "UPDATE $hbdb->ident SET description='$description', api_key='$api_key', status='$status', stat_mode='$stat_mode', stat_pass='$stat_pass' WHERE ident_id=$ident_id";
		}
		$hbdb->query($sql);
		return $hbdb->insert_id;
	}
	private function _default_value(&$var1,$value1) {
		if (empty($var1)) {
			$var1 = $value1;
		}
	}
	private function _gen_api_key($length = 12) {
		//it is only a random string
		$o = sprintf("%d-%d", time(), rand(10,99));
		$o = md5($o);
		return substr($o, 6, 6+$length);
	}
	
}
$idents = new HB_Ident;
?>